﻿/* 
 * Copyright 2010 Justin Pealing
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

using System;
using System.IO;
using Minnow.Web.Http;
using System.Text;

namespace Minnow.Web
{
    /// <summary>
    /// Handles directory listings.
    /// </summary>
    public class DirectoryHandler : RequestHandler
    {
        private static string FolderLine
        {
            get
            {
                return ResourceUtil.GetResource("Minnow.Web.HtmlContent.DirectoryListing_FolderLine.htsnippet");
            }
        }

        private static string FileLine
        {
            get
            {
                return ResourceUtil.GetResource("Minnow.Web.HtmlContent.DirectoryListing_FileLine.htsnippet");
            }
        }

        private static string PageContent
        {
            get
            {
                return ResourceUtil.GetResource("Minnow.Web.HtmlContent.DirectoryListing.html");
            }
        }

        #region IHttpHandler Members

        public override void Process(IHttpRequest Request, IHttpResponse Response, string FilePath)
        {
            StringBuilder sb = new StringBuilder();

            DirectoryInfo directoryInfo = new DirectoryInfo(FilePath);
            foreach (DirectoryInfo directory in directoryInfo.GetDirectories())
            {
                string lineString = FolderLine.Replace("{0}", directory.Name);
                sb.Append(lineString);
            }

            foreach (FileInfo file in directoryInfo.GetFiles())
            {
                string lineString = FileLine.Replace("{0}", file.Name);
                lineString = lineString.Replace("{1}", file.Length.ToString());
                sb.Append(lineString);
            }

            string parentDirectory = "";
            string currentDirectory = "";
            using (StreamWriter writer = new StreamWriter(Response.OutputStream))
            {
                string documentString = PageContent.Replace("{0}", parentDirectory);
                documentString = documentString.Replace("{1}", currentDirectory);
                documentString = documentString.Replace("{2}", sb.ToString());
                writer.WriteLine(documentString);
            }
        }

        #endregion
    }
}
